package cc.ichoice2.web.buss.system.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cc.ichoice2.web.buss.request.service.requestService;
import cc.ichoice2.web.common.Constants;


/**
 * 微信Controller
 * @author twg
 *
 */
@Controller
@RequestMapping("/weChatController.do")
public class WeChatController {
	static Logger log = Logger.getLogger(WeChatController.class);
	/**
	 * 
	 * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	 * @param timestamp 时间戳
	 * @param nonce 随机数
	 * @param echostr 随机字符串
	 */
	@RequestMapping(value={"weChat",""})
	public void weChat(
			@RequestParam(value="signature",required=false) String signature,
			@RequestParam(value="timestamp",required=false) String timestamp,
			@RequestParam(value="nonce",required=false) String nonce,
			@RequestParam(value="echostr",required=false) String echostr,
			HttpServletRequest request,
			HttpServletResponse response){
		log.info("signature:="+signature+" timestamp:="+timestamp+" nonce:="+nonce+" echostr:="+echostr);
		PrintWriter out = null;
		if(StringUtils.isNotBlank(signature) && 
				StringUtils.isNotBlank(timestamp) && 
				StringUtils.isNotBlank(nonce) && 
				StringUtils.isNotBlank(echostr)){//验证URL有效性
			String[] values = { Constants.WEIXIN_TOKEN, timestamp, nonce };
			Arrays.sort(values);// 字典序排序
			String sign = DigestUtils.sha1Hex(values[0] + values[1] + values[2]);
			try {
				out = response.getWriter();
				if(signature.equals(sign)){
					out.write(echostr);// 验证成功返回ehcostr
				}else{
					out.write("error");
				}
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				out.close();
			}
		}else{
			try {
				out = response.getWriter();
				out.write(requestService.processRequest(request));
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				out.close();
			}
			
		}
		
		
		
		
	}
	

}
